<?php

namespace api;

use think\facade\Db;
use think\facade\Request;
use app\common\model\Mobile;

/**
 * 惠花卡
 */
class Huihuakf
{
    private $appId = '';
    private $appKey = '';
    private $url = '';
    private $accessTokenKey = 'huihuakf_access_token_key';
    private $error = '';
    private $header = [
        'Content-Type: multipart/form-data',
    ];

    public function __construct($info)
    {
        $this->appId = $info['app_id'];
        $this->appKey = $info['app_secret'];
        $this->url = $info['url'];
    }

    /**
     * 获取 access_token
     */
    public function getAccessToken()
    {
        $val = cache($this->accessTokenKey);
        $now = time();
        if (!empty($val['access_token']) && $val['expire_at'] > $now) {
            return $val['access_token'];
        }

        $params = [
            'app_id' => $this->appId,
            'app_key' => $this->appKey,
            'sign' => $this->getSign(),
        ];
        $url = $this->url . '/api/open/access_token?' . http_build_query($params);
        $res = curlGet($url, $this->header);
        $res = json_decode($res, true) ?? [];
        if (!empty($res['data']['access_token'])) {
            $data = [
                'access_token' => $res['data']['access_token'],
                'expire_at' => $now + $res['data']['expires_in'] - 1000,
            ];
            cache($this->accessTokenKey, $data, $res['data']['expires_in']);
            return $res['data']['access_token'];
        }
        cache($this->accessTokenKey, null);
        return false;
    }

    /**
     * 直充商品列表
     */
    public function getRechargeList()
    {
        $accessToken = $this->getAccessToken();
        if (false === $accessToken) {
            $this->error = '获取 Access Token 失败，请重试';
            return false;
        }

        $params = [
            'app_id' => $this->appId,
            'access_token' => $accessToken,
        ];
        $url = $this->url . '/api/open/getrechargelist?' . http_build_query($params);
        $res = curlGet($url, $this->header);
        $res = json_decode($res, true) ?? [];
        if ($res['code'] == 100 && $res['message'] == 'access_token错误') {
            cache($this->accessTokenKey, null);
        }
        return $res;
    }

    /**
     * 卡卷商品列表
     */
    public function getTicketList()
    {
        $accessToken = $this->getAccessToken();
        if (false === $accessToken) {
            $this->error = '获取 Access Token 失败，请重试';
            return false;
        }

        $params = [
            'app_id' => $this->appId,
            'access_token' => $accessToken,
        ];
        $url = $this->url . '/api/open/getticketlist?' . http_build_query($params);
        $res = curlGet($url, $this->header);
        $res = json_decode($res, true) ?? [];
        if ($res['code'] == 100 && $res['message'] == 'access_token错误') {
            cache($this->accessTokenKey, null);
        }
        return $res;
    }

    /**
     * 直充商品详情
     */
    public function getRechargeDetail()
    {
        $accessToken = $this->getAccessToken();
        if (false === $accessToken) {
            $this->error = '获取 Access Token 失败，请重试';
            return false;
        }
        $params = [
            'app_id' => $this->appId,
            'access_token' => $accessToken,
            'g_id' => 56, // 56三网话费充值 97大额折扣话费
        ];
        $url = $this->url . '/api/open/getrechargedetail?' . http_build_query($params);
        $res = curlGet($url, $this->header);
        $res = json_decode($res, true) ?? [];
        if ($res['code'] == 100 && $res['message'] == 'access_token错误') {
            cache($this->accessTokenKey, null);
        }
        return $res;
    }

    /**
     * 充值下单接口
     * Array
     *  (
     *      [code] => 200
     *      [message] => 下单成功
     *      [data] => 1966163160349586245017381
     *  )
     */
    public function createOrder()
    {
        $accessToken = $this->getAccessToken();
        if (false === $accessToken) {
            $this->error = '获取 Access Token 失败，请重试';
            return false;
        }
        // 中石化：1000 1132 0002 4899 794
        $params = [
            'app_id' => $this->appId,
            'access_token' => $accessToken,
            'sign' => $this->getSign(),
            'type' => 'recharge',
            'account' => '1000113200024899794',
            'g_id' => '76', // 56三网话费充值 97大额折扣话费
            'spec_id' => '512',
            'out_order_num' => '4',
            'buy_num' => '1',
        ];
        $url = $this->url . '/api/open/createorder';
        $res = curlPost($url, $params, $this->header);
        $res = json_decode($res, true) ?? [];
        if ($res['code'] == 100 && $res['message'] == 'access_token错误') {
            cache($this->accessTokenKey, null);
        }
        return $res;
    }

    /**
     * 订单支付接口
     */
    public function recharge()
    {
        $accessToken = $this->getAccessToken();
        if (false === $accessToken) {
            $this->error = '获取 Access Token 失败，请重试';
            return false;
        }
        $params = [
            'app_id' => $this->appId,
            'access_token' => $accessToken,
            'sign' => $this->getSign(),
            // 'order_num' => '1966163160349586245017381',
            // 'order_num' => '3825163160904886245017283',
            'order_num' => '7339163176062686245017807',
        ];
        $url = $this->url . '/api/open/recharge';
        $res = curlPost($url, $params, $this->header);
        $res = json_decode($res, true) ?? [];
        if ($res['code'] == 100 && $res['message'] == 'access_token错误') {
            cache($this->accessTokenKey, null);
        }
        return $res;
    }

    /**
     * 查询订单
     */
    public function orderInfo()
    {
        $accessToken = $this->getAccessToken();
        if (false === $accessToken) {
            $this->error = '获取 Access Token 失败，请重试';
            return false;
        }
        $params = [
            'app_id' => $this->appId,
            'access_token' => $accessToken,
            // 'order_num' => '1966163160349586245017381',
            'order_num' => '3825163160904886245017283',
            'out_order_num' => '1',
        ];
        $url = $this->url . '/api/open/orderinfo';
        $res = curlPost($url, $params, $this->header);
        $res = json_decode($res, true) ?? [];
        if ($res['code'] == 100 && $res['message'] == 'access_token错误') {
            cache($this->accessTokenKey, null);
        }
        return $res;
    }

    /**
     * 创建订单
     *
     * @params
     * sub_order_id 系统订单号
     * amount 充值金额
     * mobile 充值号码
     * 
     * $return  false/供应商订单号
     */
    public function create($order)
    {
        // 下单之前，先查询是否已经有相同订单号的订单了，防止重复下单
        $query = $this->query($order['sub_order_id']);
        // 已经下过单了
        if (!empty($query['data']['order_id'])) {
            return $query['data']['order_id'];
        }

        $url = $this->url . '/api/mobile';
        $params = [
            'type' => 'quanmama.mobile.order',
            'app_key' => $this->appId,
            'mobile' => $order['mobile'],
            'out_trade_no' => $order['sub_order_id'],
            'amount' => fen2yuan($order['amount']),
            'timestamp' => time(),
            'notify' => env('app.api_url') . '/api/notify/quanmamaNotify',
            'isFast' => $order['order_type'] == 1 ? 0 : 1,
        ];
        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, $params, $this->header);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 查询余额
     * 
     * 单位：分
     */
    public function queryAmount()
    {
        $accessToken = $this->getAccessToken();
        if (false === $accessToken) {
            $this->error = '获取 Access Token 失败，请重试';
            return false;
        }
        $params = [
            'app_id' => $this->appId,
            'app_key' => $this->appKey,
        ];
        $url = $this->url . '/api/open/get_usermoney';
        $res = curlPost($url, $params, $this->header);
        $res = json_decode($res, true) ?? [];
        if ($res['code'] == 100 && $res['message'] == 'access_token错误') {
            cache($this->accessTokenKey, null);
            $this->error = '查询频繁';
            return false;
        }
        
        if ($res['code'] != 200) {
            $this->error = $res['message'] ?? '查询频繁';
            return false;
        }
        return yuan2fen($res['data']);
    }

    /**
     * 订单查询
     */
    public function query($orderId)
    {
        $url = $this->url . '/api/mobile';
        $params = [
            'type' => 'quanmama.mobile.order.query',
            'app_key' => $this->appId,
            'out_trade_no' => $orderId,
            'timestamp' => time(),
        ];
        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, $params, $this->header);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 生成签名
     */
    public function getSign()
    {
        $str = $this->appId . $this->appKey;
        return strtolower(md5($str));
    }

    public function getError()
    {
        return $this->error;
    }
}
